package com.example.apple.paopo.fragment.world;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.apple.paopo.R;
import com.example.apple.paopo.adapter.mFoundAdapter;
import com.example.apple.paopo.base.BaseFragment;
import com.example.apple.paopo.model.FoundModel;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.vondear.rxtools.view.RxToast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;

import static android.content.Context.MODE_APPEND;

/**
 * Created by apple on 17/12/10.
 */
//发现
    @ContentView(R.layout.fragment_found)
public class FoundFragment extends BaseFragment {

    @ViewInject(R.id.found_refreshLayout)
    RefreshLayout refreshLayout;
    @ViewInject(R.id.found_recyclerview)
    RecyclerView recyclerView;

    ArrayList<FoundModel> mdatas;

    com.example.apple.paopo.adapter.mFoundAdapter mFoundAdapter;

    SharedPreferences sharedPreferences;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view= x.view().inject(this,inflater,container);
        sharedPreferences =getContext().getSharedPreferences("PAOPO",MODE_APPEND);
        initView(view);
//        sharedPreferences =getActivity().getSharedPreferences("PAOPO",MODE_APPEND);
        return view;
    }

    private void initView(View view) {
        setUpRecyclerView();
        setUpRefreshAndLoadmore();
        refreshLayout.autoRefresh();
    }
    private void initDatas(final RefreshLayout refreshlayout) {
        RequestParams params = new RequestParams("http://cloud.bmob.cn/91c9d2dffacfcd37/worldMessageFoundListObtainAction");
        params.addQueryStringParameter("token",sharedPreferences.getString("token",""));
        params.addQueryStringParameter("page","0");
        x.http().get(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject =new JSONObject(result);
                    if (jsonObject.getString("state").equals("YES")){
                        JSONObject data = new JSONObject(jsonObject.getString("msge"));
                        final JSONArray dataarr =data.getJSONArray("results");
                        Gson gson = new Gson();
                        // 可以通过GsonBuilder配置多种选项
//                         .setLenient()// json宽松
                        gson = new GsonBuilder()
                                .enableComplexMapKeySerialization()// 支持Map的key为复杂对象的形式
                                .serializeNulls() // 智能null
                                .setPrettyPrinting()// 调教格式
                                .disableHtmlEscaping() // 默认是GSON把HTML 转义的
                                .create();
                                mdatas.clear();
                                for (int i =0;i<dataarr.length();i++){
                                    FoundModel foundModel = null;
                                    foundModel = gson.fromJson(dataarr.get(i).toString(),FoundModel.class);
                                    mdatas.add(foundModel);
                                }

                    }else {
                        RxToast.error("网络错误，请联系管理员"+jsonObject.getString("msge"));
                    }
                    Logger.d("数据"+mdatas.size());
                    mFoundAdapter.notifyDataSetChanged();
                    refreshlayout.finishRefresh();

                } catch (JSONException e) {
                    e.printStackTrace();
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mFoundAdapter.notifyDataSetChanged();
                            refreshlayout.finishRefresh();
                        }
                    });
                    RxToast.error("解析错误，请联系管理员"+e.toString());
                }
//                Logger.d(result);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                mFoundAdapter.notifyDataSetChanged();
                refreshlayout.finishRefresh();
                RxToast.error("网络错误，请联系管理员"+ex.toString());
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

    }

    private void setUpRecyclerView() {
        mdatas= new ArrayList<>();
        mFoundAdapter= new mFoundAdapter(getContext(),mdatas);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
//设置布局管理器
        recyclerView.setLayoutManager(layoutManager);
//设置为垂直布局，这也是默认的
        layoutManager.setOrientation(OrientationHelper. VERTICAL);
//设置Adapter
        recyclerView.setAdapter(mFoundAdapter);
//        //设置分隔线
//        recyclerView.addItemDecoration(new DividerGridItemDecoration(getContext()));
//设置增加或删除条目的动画
        recyclerView.setItemAnimator(new DefaultItemAnimator());
    }

    private void setUpRefreshAndLoadmore() {
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                initDatas(refreshlayout);

            }
        });
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                RxToast.success("我要开始了");
                refreshlayout.finishLoadmore(2000/*,false*/);//传入false表示加载失败
                mFoundAdapter.notifyDataSetChanged();
            }
        });
    }
}
